package com.mbyte.easy.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mbyte.easy.admin.entity.CheckPartner;
import com.mbyte.easy.admin.mapper.CheckPartnerMapper;
import com.mbyte.easy.admin.service.ICheckPartnerService;
import com.mbyte.easy.common.controller.BaseController;
import com.mbyte.easy.common.web.AjaxResult;
import com.mbyte.easy.security.entity.SysUser;
import com.mbyte.easy.security.mapper.SysUserMapper;
import com.mbyte.easy.security.service.IUserService;
import com.mbyte.easy.util.PageInfo;
import com.mbyte.easy.util.Utility;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassNameModuleLeaderController
 * @Description 版块负责人分配互查伙伴
 * @Author myr
 * @Date 2019/12/9 22:05
 * @Version 1.0
 **/
@Slf4j
@Controller
@RequestMapping("/partner/moduleLeader")
public class ModuleLeaderController extends BaseController {

    private String prefix = "admin/partner/";

    @Autowired
    private ICheckPartnerService checkPartnerService;
    @Autowired
    private CheckPartnerMapper checkPartnerMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private SysUserMapper sysUserMapper;


    /**
     * 版块负责人查看自己的组员列表
     * @param model
     * @param pageNo
     * @param pageSize
     * @param name
     * @return
     */
    @RequestMapping
    public String index(Model model,
                        @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                        @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize,
                        @RequestParam(value = "name", required = false, defaultValue = "") String name) {
        SysUser user = new SysUser();
        QueryWrapper<CheckPartner> queryWrapper = new QueryWrapper<>();
        if (name != null && !"".equals(name.trim())) {
            user.setUsername(name);
            model.addAttribute("name", name.trim());
        }
        String loginUserName = Utility.getCurrentUsername();
        SysUser loginUser = sysUserMapper.selectByUsername(loginUserName);
        Long modulLeaderId = loginUser.getId();

        queryWrapper.eq("module_leader",modulLeaderId);
        List<CheckPartner> checkPartnerList = checkPartnerMapper.selectList(queryWrapper);
        Map<Long,String> types = new HashMap<Long,String>();
        List<Long> ids = new ArrayList<>();
        for(CheckPartner checkPartner:checkPartnerList){
            if(!ids.contains(checkPartner.getUserId())) {
                ids.add(checkPartner.getUserId());
                if (userService.selectByPrimaryKey(checkPartner.getPartnerId()) != null){
                    //key user_id , value 伙伴的username
                    types.put(checkPartner.getUserId(), userService.selectByPrimaryKey(checkPartner.getPartnerId()).getUsername());
                }
            }
        }
        model.addAttribute("name1",types);
        model.addAttribute("pageInfo", new PageInfo<SysUser>(checkPartnerService.index(pageNo,pageSize,name,model)));
        return this.prefix + "partner-list";
    }

    /**
     * 添加跳转页面
     * @ 用户表id--userId
     * @return
     */
    @GetMapping("addBefore/{id}")
    public String addBefore(Model model,@PathVariable("id")Long id){
        List<SysUser> userList = checkPartnerService.addBefore(id);
        CheckPartner partner = checkPartnerService.getPartner(id);
        model.addAttribute("partnerId", ObjectUtils.isEmpty(partner)?null:partner.getPartnerId());
        model.addAttribute("checkPartanerId",ObjectUtils.isEmpty(partner)?null:partner.getId());
        model.addAttribute("writerList",userList.isEmpty()?-1:userList);
        model.addAttribute("userId",id);
        model.addAttribute("moduleLeaderId",checkPartnerService.getCurrentUser().getId());
        return prefix+"add";

    }

    /**
     * 分配互查伙伴，可编辑，已存在就更新，不存在则插入
     * 不能保证一对一关系 @_@
     * @return
     */
    @PostMapping("add")
    @ResponseBody
    public AjaxResult add(CheckPartner checkPartner){
        log.info("The checkPartner is --> {}",checkPartner);
        boolean result = true;
        QueryWrapper<CheckPartner> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",checkPartner.getUserId());
        CheckPartner user = checkPartnerService.getOne(queryWrapper);
        user.setPartnerId(checkPartner.getPartnerId());
        log.info("user---------->{}",user);
        checkPartner.setUpdateTime(LocalDateTime.now());
        checkPartner.setCreateTime(LocalDateTime.now());
        //互查伙伴为空
        if ( user.getPartnerId() == null){
            checkPartnerService.updateById(user);
            result =  checkPartnerService.updateById(user);
        }else {
            checkPartner.setId(user.getId());
            result = checkPartnerService.updateById(checkPartner);
        }
        return toAjax(result);
    }

    /**
     * 添加跳转页面
     * @return
     */
    @GetMapping("editBefore/{id}")
    public String editBefore(Model model,@PathVariable("id")Long id){
       if(id != null){
           SysUser sysUser = sysUserMapper.selectByPrimaryKey(id);
           model.addAttribute("user",sysUser);
       }
       setSexType(model);
        return prefix+"edit";
    }
    /**
     * 性别回显
     * @param model
     */
    public void setSexType(Model model){
        Map<Integer,String> status = new HashMap<Integer,String>();
        status.put(1,"男");
        status.put(0,"女");
        model.addAttribute("sexType",status);
    }

    @PostMapping("edit")
    @ResponseBody
    public AjaxResult edit(SysUser user){
        log.info("实体-->{}",user.toString());
        if(!ObjectUtils.isEmpty(user)) {
            int update = sysUserMapper.updateByPrimaryKeySelective(user);
            log.info("ajax-->{}",update);
            return toAjax(true);
        }
        return toAjax(false);
    }
}
